package cn.qiyu5522.filters;

import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.constant.SystemConsKeys;
import cn.qiyu5522.domain.entity.LoginUser;
import cn.qiyu5522.domain.entity.ResponseResult;
import cn.qiyu5522.enums.AppHttpCodeEnum;
import cn.qiyu5522.utils.JwtUtil;
import cn.qiyu5522.utils.RedisCache;
import cn.qiyu5522.utils.WebUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: JwtAuthenticationTokenFilter
 * Package: cn.qiyu5522.filters
 * Description: 定义Jwt认证过滤器
 *
 * @Author: Tonkey
 * @Create：2024/4/12-10:33
 * @Version: v1.0
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = request.getHeader("token");
        if(!StringUtils.isNotEmpty(token)){
            // 该接口不需要登录，直接放行，由后面的过滤器处理
            filterChain.doFilter(request,response);
            // 过滤器链，返回后，不执行下面的代码
            return;
        }
        //解析获取userid
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            // token 超时 token 非法
            // 响应告诉前端需要重新登录,这里没有到controller 层，所以不会被统一异常处理监听
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, objectMapper.writeValueAsString(responseResult));
            return;
        }
        String userId = claims.getSubject();
        // 从 Redis 中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(SystemConsKeys.BLOG_LOGIN + userId);
        if(!ObjectUtil.isNotEmpty(loginUser)){
            // 说明登录过期 ，提示重新登录
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, objectMapper.writeValueAsString(responseResult));
            return;
        }

        // 存入 SecurityContextHolder
        // UsernamePasswordAuthenticationToken 构造三个参数的，代表用户以认证
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request,response);
    }
}
